#include "myfile.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>
#include <unistd.h>

int myfflush(My_FILE* fp)
{
  assert(fp);

  //将缓冲区内容刷新到指定的文件
  write(fp->fd, fp->outputbuffer, fp->current);//文件不识别\0，因此不用+1
  fp->current = 0;
 
  return 0;
}

My_FILE* myfopen(const char *path, const char *mode)
{
  int flag = 0;

  if(strcmp(mode, "r") == 0) 
    flag |= O_RDONLY;
  else if(strcmp(mode, "w") == 0) 
    flag |= O_WRONLY|O_CREAT|O_TRUNC;
  else if(strcmp(mode, "a") == 0) 
    flag |= O_WRONLY|O_CREAT|O_APPEND;
  else{}

  int m = 0666;//默认创建文件权限
  int fd = 0;

  //调用系统接口
  if(flag & O_CREAT) 
    fd = open(path, flag, m);
  else 
    fd = open(path, flag);

  if(fd <0) 
  {
    //文件打开失败
    perror("open\n");
    return NULL;
  }

  //成功打开文件，创建文件结构体
  My_FILE* fp = (My_FILE*)malloc(sizeof(My_FILE));
  if(fp == NULL)
  {
    perror("malloc\n");
    close(fd);
    return NULL;
  }
  
  //初始化
  fp->fd = fd;
  fp->flag = 0;
  fp->current = 0;
  fp->flag |= BUFFELINE;//默认设置为行缓冲
  memset(fp->outputbuffer, '\0', sizeof(fp->outputbuffer));

  return fp;
}

int myfclose(My_FILE* fp)
{
  assert(fp);
  
  //刷新缓冲区
  if(fp->current > 0) myfflush(fp);
  
  close(fp->fd);
  
  //防止内存泄漏
  free(fp);
  fp = NULL;
  
  return 0;
}

size_t myfwrite(const void* ptr, size_t size, size_t nmemb, My_FILE* fp)
{
  assert(fp);
 
  //if()
    

  return 0;
}














